<template>
    <DialogCom :draggable="true" :title="title" :width="'500'" :visible="isVisible" @close="close" @confirm="confirm">
        <template v-slot:content>
            <div class="source">
                <span @click="currentSource = 'lib'" :class="{ 'actived': currentSource == 'lib' }">资源库</span>
                /
                <span @click="currentSource = 'dataset'" :class="{ 'actived': currentSource == 'dataset' }">数据集</span>
            </div>
            <div class="lib-content" v-if="currentSource == 'lib'" ref="container">
                <div v-for="(item, index) in geometryRef" :key="index" @click="currentChange(item, index)"
                    class="img-box">
                    <div class="img" :class="{ 'is-active': isHighLight == index }">
                        <!-- <img :src="`data:image/jpeg;base64,${item.thumb}`" alt=""> -->
                        <div class="preview-image"
                            v-if="item.thumb !== null && item.thumb !== undefined && item.thumb !== ''">
                            <img :src="`data:image/jpeg;base64,${item.thumb}`" alt="预览图" class="preview-image" />
                        </div>
                        <div v-else class="preview-image" @click="showThumb(item.id, 'resource_libary')">
                            <div class="inner-div"></div>
                        </div>
                    </div>
                    <div class="name" :title="item.name">{{ item.name }}</div>
                </div>
            </div>
            <div class="dataset-content" v-if="currentSource == 'dataset'">
                <div class="xbsj-table">
                    <el-table :data="dataSetRef" border :cell-style="cellStyle" :header-cell-style="headCellStyle"
                        highlight-current-row @row-click="handleRowClick" :max-height="300" ref="selectAppTable">
                        <el-table-column type="index" label="序号" width="60" align="center"
                            :show-overflow-tooltip="true" />
                        <el-table-column prop="id" label="几何体ID" :show-overflow-tooltip="true" />

                        <el-table-column label="缩略图" width="auto" align="center">
                            <template #default="{ row }">
                                <div class="preview-image"
                                    v-if="row.thumb !== null && row.thumb !== undefined && row.thumb !== ''">
                                    <img style='width:50px !important;height:50px !important;'
                                        :src="`data:image/jpeg;base64,${row.thumb}`" alt="预览图" class="preview-image" />
                                </div>
                                <div v-else class="preview-image" @click="showThumb(row.id)">
                                    <div class="inner-div"></div>
                                </div>
                            </template>
                        </el-table-column>
                    </el-table>
                </div>
                <div class="bottom">
                    <PaginatorCom :currentPage="pages.pageNum" :pageSize="pages.pageSize" :total="total"
                        @update:currentPage="handleCurrentChange" @update:pageSize="handleSizeChange" />
                </div>
            </div>
        </template>
    </DialogCom>
</template>
<script setup lang="ts">
import DialogCom from "@/components/common/DialogCom.vue";
import { watch, ref, onBeforeUnmount, onMounted, nextTick } from "vue";
import { getProjectManager } from "@/scripts/getProjectManager";
import {
    createVueDisposer,
    toVR,
} from "earthsdk-ui";
import { cellStyle, headCellStyle, cellStyleSmall, cellStyle2, } from "@/scripts/tableStyle";
import PaginatorCom from '@/components/common/PaginatorCom.vue';
import { reqCreateGltfThumb } from '@/api';

import { ElMessage } from "element-plus";
import loading from "../../api/loading";

const props = defineProps({
    isVisible: {
        type: Boolean,
        default: false,
    },
    close: {
        type: Boolean,
        default: false,

    },
    title: {
        type: String,
        default: "",
    },
    isGeometryId: {
        type: String,
        default: "",
    },
    currentDataSet: {
        type: String,
        default: "",
    }
});

const d = createVueDisposer(onBeforeUnmount);
const cimrtsManager = getProjectManager().cimrtsManager;



const batchSet = cimrtsManager.batchSet as any
// cimrts服务ip

const total = ref(0)
const pages = ref({ pageNum: 1, pageSize: 5, })

// 几何库列表
const geometryRef = toVR<any>(d, [batchSet, "geometryLib"]);

// 数据源类型
const sourceTypeRef = toVR<any>(d, [batchSet, "sourceType"])

const isHighLight = ref(-1)
const emits = defineEmits(["close", "confirm"]);
const idname = ref({ id: "", name: "", sourceType: '' })

const container = ref<any>(null)

// 数据集列表
const dataSetRef = ref([]);

// 当前选中的数据源
const currentSource = ref("lib")

const currentChange = (item: any, index: number) => {
    isHighLight.value = index
    idname.value.id = item.id
    idname.value.name = item.name
    idname.value.sourceType = 'lib'

}

const selectAppTable: any = ref(null)

// 单击 列表上选择正在编辑的对象
const handleRowClick = async (row: any) => {
    idname.value.id = row.id
    idname.value.name = row.name
    idname.value.sourceType = 'dataset'

    nextTick(() => {
        selectAppTable.value?.setCurrentRow(row);
    });
}


/**
 * 监听当前页数变化
 * @param {number} val 
 */
const handleCurrentChange = async (val: any) => {
    pages.value.pageNum = val;
    //获取要素列表
    await getList()
}
/**
 * 监听当前页条数变化
 * @param {number} val 
 */
const handleSizeChange = async (val: any) => {
    pages.value.pageSize = val;
    //获取要素列表
    await getList()
}

// 关闭按钮
const close = () => {
    emits('close')
}
// 确认
const confirm = async () => {
    emits('confirm', idname.value)

}

//更新缩略图
const showThumb = async (id: string, type?: string) => {
    try {
        const data = {
            datasetName: type ? type : props.currentDataSet,
            geometryId: id,
        }
        const res = await reqCreateGltfThumb(data)
        // @ts-ignore
        if (res.status !== 'ok') {
            loading.closeLoading()
            ElMessage({
                message: "生成几何体缩略图失败",
                type: 'error',
            })
        }
        ElMessage.success('生成几何体缩略图成功')
        loading.closeLoading()
        if (type) {
            await batchSet.geometryLibList()
        } else {
            await getList()                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 
        }

    } catch (error) {
        loading.closeLoading()
        console.error(error)
    }
}

//获取要素列表
const getList = async () => {
    const param = {
        datasetName: props.currentDataSet,
        ...pages.value,
    }
    const data = await batchSet.getFeatureList(param) as any
    dataSetRef.value = data.tableData
    total.value = data.total
}

onMounted(async () => {
    if (!props.isGeometryId) {
        // 获取几何列表

        await batchSet.geometryLibList()
        //获取要素列表
        await getList()
    }

    // 资源库高亮逻辑
    if (props.isGeometryId && sourceTypeRef.value == 'lib') {
        nextTick(() => {
            // 高亮当前行
            const index = geometryRef.value.findIndex((item: any) => item.id == props.isGeometryId)
            currentChange(geometryRef.value[index], index)
            // 目标行
            const currentRow = Math.floor((index + 1) / 4)
            // 滚动距离
            const scrollTop = currentRow * 150
            container.value.scrollTo({ top: scrollTop, behavior: 'smooth' })

            //获取要素列表
            getList()
        })
    }

    // 数据集高亮逻辑
    if (props.isGeometryId && sourceTypeRef.value == 'dataset') {
        currentSource.value = 'dataset'
        const param = {
            datasetName: props.currentDataSet,
            pageNum: 1,
            pageSize: 100000000,
        }
        // 获取几何体列表
        const res = await batchSet.getFeatureList(param) as any
        // 高亮当前行
        const index = res.tableData.findIndex((item: any) => item.id == props.isGeometryId)
        pages.value.pageNum = index ? Math.ceil((index + 1) / Number(pages.value.pageSize)) : 1

        await getList()

        setTimeout(() => {
            const index = dataSetRef.value.findIndex((item: any) => item.id == props.isGeometryId)
            index != undefined && selectAppTable.value?.setCurrentRow(dataSetRef.value[index])
        }, 50)
    }
})
</script>

<style scoped>
.is-active {
    border: 1px solid #409eff;
}

.lib-content {
    display: flex;
    flex-wrap: wrap;
    align-items: flex-start;
    gap: 20px 9px;
    height: 340px;
    overflow-y: auto;
}

.img-box {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    cursor: pointer;
}

.img {
    box-sizing: border-box;
    width: 100px;
    height: 100px;
    padding: 10px;
}

.img img {
    width: calc(100%);
    height: calc(100%);
}

.name {
    width: 80px;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
    padding: 5px 0;
    text-align: center;
}

.select-table {
    height: calc(100% - 60px);
    display: flex;
    flex-direction: column;
    justify-content: space-between
}

.actived {
    color: #8383ff;
}

.source {
    margin-bottom: 15px;
}

.source>span {
    cursor: pointer;
}

.dataset-content {
    display: flex;
    flex-direction: column;
    height: 340px;
    justify-content: space-between;
}

.bottom {
    display: flex;
    justify-content: center;
}

.preview-image {
    width: 100%;
    height: 100%;
    cursor: pointer;
    display: flex;
    align-items: center;
    justify-content: center;

}

.preview-image .inner-div {
    width: 60px;
    height: 60px;
    cursor: pointer;
    background-image: url(../../assets/cimrts/batchPlace/previewmoren.svg);
    background-size: cover;
    background-repeat: no-repeat;
    /* 防止重复 */
    background-position: center;
    /* 水平 + 垂直居中 */
}

.preview-image:hover .inner-div {
    background-image: url(../../assets/cimrts/batchPlace/previewxuanfu.svg) !important;
}
</style>